package de.zainodis.kitchengnome.ui.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import de.zainodis.kitchengnome.R;
import de.zainodis.kitchengnome.domainmodel.Suggestion;

public class SuggestionListAdapter extends SortableListAdapter {

	private static final String TAG = "SuggestionListAdapter";

	private ArrayList<Suggestion> entries;
	private LayoutInflater layoutInflater;

	public SuggestionListAdapter(Context context, ArrayList<Suggestion> entries) {
		this.entries = entries;
		this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		sort();
	}

	@Override
	public int getCount() {
		return entries != null ? entries.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return entries.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (convertView == null) {
			view = layoutInflater.inflate(R.layout.layout_list_row, null);
		}

		// Retrieve item at given position
		Suggestion entry = entries.get(position);

		// Set name of item
		TextView nameField = (TextView) view.findViewById(R.id.layout_list_row_name);
		nameField.setText(entry.getName());

		return view;
	}

	public ArrayList<Suggestion> getEntries() {
		return entries;
	}

	public void update(ArrayList<Suggestion> newItems) {
		entries = newItems;
		notifyDataSetChanged();
	}

	public void add(Suggestion suggestion) {
		entries.add(suggestion);
		sort();
	}

	public Suggestion delete(int position) {
		Suggestion removed = entries.remove(position);
		sort();
		return removed;
	}

	public void sort() {
		super.sort(entries);
	}
}
